<template>
    <div class="server-time" title="服务器时间">
        <span v-if="display">{{ display }}</span>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { getServerTime } from '@/api/system/server'

// 更新时间间隔（ms），每次从服务器重新同步的周期
const SYNC_INTERVAL = 60 * 1000 // 60s

const display = ref('')
const serverTs = ref<number>(Date.now())
let tickTimer: number | null = null
let syncTimer: number | null = null

function formatTs(ts: number) {
    if (!ts) return ''
    const d = new Date(ts)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hh = String(d.getHours()).padStart(2, '0')
    const mm = String(d.getMinutes()).padStart(2, '0')
    const ss = String(d.getSeconds()).padStart(2, '0')
    return `${y}-${m}-${day} ${hh}:${mm}:${ss}`
}

async function syncServerTime() {
    let res: any = await getServerTime()
    display.value = formatTs(res.data)
}

function startTick() {
    if (tickTimer != null) return
    tickTimer = window.setInterval(() => {
        serverTs.value += 1000
        display.value = formatTs(serverTs.value)
    }, 1000)
}

function stopTick() {
    if (tickTimer != null) {
        clearInterval(tickTimer)
        tickTimer = null
    }
}

onMounted(async () => {
    await syncServerTime()
    startTick()
    // 定时重新同步，防止漂移
    syncTimer = window.setInterval(async () => {
        await syncServerTime()
    }, SYNC_INTERVAL)
})

onBeforeUnmount(() => {
    stopTick()
    if (syncTimer != null) {
        clearInterval(syncTimer)
        syncTimer = null
    }
})
</script>

<style scoped>
.server-time {
    display: inline-flex;
}
</style>
